package com.example.demo.handle;

import com.example.demo.enums.ResponseCode;
import com.example.demo.common.ServerResponse;
import com.example.demo.exception.StudentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by gf on 2018/10/20.
 */
@ControllerAdvice //标注的类为异常处理类
public class ExceptionHandle {

    private static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = Exception.class) //标注的当前方法为异常处理方法
    @ResponseBody
    private ServerResponse handle(Exception e){
        if(e instanceof StudentException){
            StudentException se = (StudentException)e;
            return ServerResponse.createByErrorCodeMessage(se.getCode(),se.getMessage());
        }
        logger.info("【异常信息】:{}",e);
        return ServerResponse.createByErrorCodeMessage(ResponseCode.ERROR_EXCEPTION.getCode(),ResponseCode.ERROR_EXCEPTION.getDesc());
    }
}
